<?php
/**
 * 获取 用户信息
 */

namespace app\api\model;

use think\Db;
use app\common\model\Model;

class User extends  Model
{
    const TABLE_NAME = 'userinfo';
    const CACHE_EXPIRE_LEVEL = self::CACHE_EXPIRE_LEVEL_1;

    protected $name = self::TABLE_NAME;

    const DEFAULT_AVATAR=HOST_URL.UPLOAD_ROOT_PATH.'/avatar.png';
    public static function getUserInfo($user_id)
    {
       return self::commonQuery('user',self::CACHE_EXPIRE_LEVEL)
             ->where(['user_id'=>$user_id])
            ->find();

    }
    
    public static function getUserName($user_id)
    {
        $info = self::getUserInfo($user_id);
        return empty($info)?'':$info['user_name'];
    }
    public static function getExtendInfo($user_id,$cache=false)
    {
        return self::commonQuery(self::TABLE_NAME,$cache)
               ->where(['user_id'=>$user_id])
               ->find();
    }
    //在 扣除 用户 积分 时 调用
    public static function getUserPointsForUpdate($user_id)
    {
        $sql="select available_points  from userinfo where user_id=$user_id for update";

        $info = self::query($sql);
        return empty($info)?0:$info[0]['available_points'];
    }
    //返回 用户 昵称 和 头像
    public static function handleUserCommonInfo($user_id)
    {
        $info = self::getUserInfo($user_id);
        return ['user_name'=>$info['user_name'],
                 'user_avatar'=>empty($info['user_avatar'])?self::DEFAULT_AVATAR:$info['user_avatar']];
    }
    public static function getUserIdByInviteCode($invite_code)
    {
        return self::commonQuery(self::TABLE_NAME)
               ->where(['user_invite_code'=>$invite_code])
              ->value('user_id');

    }
    public static function incrUserPoints($user_id,$points)
    {

        $sql = "INSERT INTO userinfo(`user_id`,`available_points`) VALUES ($user_id,$points) on duplicate key update `available_points` = `available_points` + $points";

       return self::execute($sql);
    }
    public static function descUserPoints($user_id,$points)
    {
        return self::commonQuery(self::TABLE_NAME)
               ->where(['user_id'=>$user_id])
               ->exp("consume_points","consume_points + $points")
               ->setDec('available_points',$points);
    }

    public static function saveUserInfo($user_id, $user_name,$user_phone,$address)
    {
        Db::startTrans();
        try{
            self::commonQuery('user')->where(['user_id'=>$user_id])
                ->update(['user_name'=>$user_name,'user_phone'=>$user_phone]);

             self::commonQuery(self::TABLE_NAME)
                 ->where(['user_id'=>$user_id])
                 ->setField('address',$address);
        }catch (\Exception $e)
        {
            Db::rollback();
            // return ($e->getMessage());
            return ['status'=>false,'msg'=>$e->getMessage()];
        }

        Db::commit();
        return ['status'=>true,'msg'=>''];
    }
  
}